<!--
  应用详情组件
  @description 查看SOP应用的详细信息，包含AppId和AppSecret
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="900px"
    :scroll="true"
    max-height="600px"
  >
    <div v-loading="loading">
      <!-- 应用基本信息 -->
      <el-card class="mb-20px">
        <template #header>
          <div class="card-header">
            <span>{{ t('sop.app.basicInfo') }}</span>
          </div>
        </template>
        <el-descriptions :column="2" border v-if="appData">
          <el-descriptions-item :label="t('sop.app.appId')">
            <el-text class="app-id-text" copyable>{{ appData.appId }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.app.appName')">
            {{ appData.appName }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.app.merchantNo')">
            {{ appData.merchantNo }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.app.merchantName')">
            {{ appData.merchantName }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.app.appStatus')">
            <el-tag :type="getAppStatusTagType(appData.appStatus)">
              {{ appStatusOptions[appData.appStatus] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.common.createTime')">
            {{ formatDate(appData.createTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 密钥信息 -->
      <el-card class="mb-20px">
        <template #header>
          <div class="card-header">
            <span>{{ t('sop.app.secretInfo') }}</span>
            <el-button
              type="danger"
              size="small"
              @click="handleResetSecret"
              :loading="resetLoading"
              v-hasPermi="['sop:app:reset-secret']"
            >
              <Icon class="mr-5px" icon="ep:refresh" />
              {{ t('sop.app.resetSecret') }}
            </el-button>
          </div>
        </template>
        <el-descriptions :column="1" border v-if="appData">
          <el-descriptions-item :label="t('sop.app.appSecret')">
            <div class="secret-container">
              <el-text v-if="showSecret" class="secret-text" copyable>
                {{ appData.appSecret }}
              </el-text>
              <el-text v-else class="secret-masked">
                {{ maskSecret(appData.appSecret) }}
              </el-text>
              <el-button link type="primary" @click="toggleSecret" class="ml-10px">
                <Icon :icon="showSecret ? 'ep:hide' : 'ep:view'" />
                {{ showSecret ? t('sop.app.hideSecret') : t('sop.app.showSecret') }}
              </el-button>
            </div>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.app.secretUpdateTime')">
            {{ formatDate(appData.secretUpdateTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 限流配置 -->
      <el-card class="mb-20px">
        <template #header>
          <div class="card-header">
            <span>{{ t('sop.app.rateLimitConfig') }}</span>
          </div>
        </template>
        <el-descriptions :column="2" border v-if="appData">
          <el-descriptions-item :label="t('sop.app.rateLimitPerSecond')">
            <el-tag type="info">{{ appData.rateLimitPerSecond }}/s</el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.app.rateLimitPerMinute')">
            <el-tag type="warning">{{ appData.rateLimitPerMinute }}/m</el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.app.tokenExpireHours')">
            <el-tag type="primary">{{ appData.tokenExpireHours }}{{ t('sop.app.hours') }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 安全配置 -->
      <el-card class="mb-20px">
        <template #header>
          <div class="card-header">
            <span>{{ t('sop.app.securityConfig') }}</span>
          </div>
        </template>
        <el-descriptions :column="1" border v-if="appData">
          <el-descriptions-item :label="t('sop.app.ipWhitelist')">
            <div v-if="appData.ipWhitelist" class="ip-list">
              <el-tag
                v-for="ip in getIpList(appData.ipWhitelist)"
                :key="ip"
                class="mr-5px mb-5px"
                type="success"
              >
                {{ ip }}
              </el-tag>
            </div>
            <el-text v-else type="info">{{ t('sop.app.noIpLimit') }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.app.notifyUrl')">
            <el-text v-if="appData.notifyUrl" copyable>{{ appData.notifyUrl }}</el-text>
            <el-text v-else type="info">{{ t('sop.app.noNotifyUrl') }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.app.webhookSecret')">
            <el-text v-if="appData.webhookSecret" class="secret-text">
              {{ showWebhookSecret ? appData.webhookSecret : maskSecret(appData.webhookSecret) }}
            </el-text>
            <el-text v-else type="info">{{ t('sop.app.noWebhookSecret') }}</el-text>
            <el-button
              v-if="appData.webhookSecret"
              link
              type="primary"
              @click="toggleWebhookSecret"
              class="ml-10px"
            >
              <Icon :icon="showWebhookSecret ? 'ep:hide' : 'ep:view'" />
            </el-button>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 备注信息 -->
      <el-card v-if="appData?.remark">
        <template #header>
          <div class="card-header">
            <span>{{ t('sop.common.remark') }}</span>
          </div>
        </template>
        <div class="remark-content">
          {{ appData.remark }}
        </div>
      </el-card>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/formatTime'
import { getAppInfoApi, resetAppSecretApi } from '@/api/sop/app'
import type { AppVO } from '@/api/sop/types'
import { AppStatusEnum } from '@/api/sop/types'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'

defineOptions({ name: 'AppDetail' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const loading = ref(false)
const resetLoading = ref(false)

// 应用数据
const appData = ref<AppVO>()

// 显示控制
const showSecret = ref(false)
const showWebhookSecret = ref(false)

// 选项数据
const appStatusOptions = {
  [AppStatusEnum.ENABLED]: t('sop.app.appStatuses.enabled'),
  [AppStatusEnum.DISABLED]: t('sop.app.appStatuses.disabled')
}

/**
 * 打开对话框
 */
const open = async (app: AppVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('sop.app.detail') + ' - ' + app.appName
  loading.value = true
  showSecret.value = false
  showWebhookSecret.value = false

  try {
    // 获取应用详情
    const data = await getAppInfoApi(app.id)
    appData.value = data
  } catch (error) {
    console.error('获取应用详情失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 切换密钥显示
 */
const toggleSecret = () => {
  showSecret.value = !showSecret.value
}

/**
 * 切换Webhook密钥显示
 */
const toggleWebhookSecret = () => {
  showWebhookSecret.value = !showWebhookSecret.value
}

/**
 * 重置密钥
 */
const handleResetSecret = async () => {
  try {
    await ElMessageBox.confirm(t('sop.app.tips.resetSecretConfirm'), t('sop.common.confirmTitle'), {
      confirmButtonText: t('sop.common.confirm'),
      cancelButtonText: t('sop.common.cancel'),
      type: 'warning'
    })

    resetLoading.value = true
    const newSecret = await resetAppSecretApi(appData.value!.id)
    appData.value!.appSecret = newSecret
    appData.value!.secretUpdateTime = new Date().toISOString()
    ElMessage.success(t('sop.app.tips.resetSecretSuccess'))
  } catch (error) {
    console.error('重置密钥失败:', error)
  } finally {
    resetLoading.value = false
  }
}

/**
 * 脱敏显示密钥
 */
const maskSecret = (secret: string) => {
  if (!secret || secret.length < 8) return secret
  return secret.substring(0, 4) + '****' + secret.substring(secret.length - 4)
}

/**
 * 获取IP列表
 */
const getIpList = (ipWhitelist: string) => {
  return ipWhitelist
    .split(/[,，\n]/)
    .map((ip) => ip.trim())
    .filter((ip) => ip)
}

// 标签类型获取函数
const getAppStatusTagType = (status: number) => {
  const statusMap = {
    [AppStatusEnum.ENABLED]: 'success',
    [AppStatusEnum.DISABLED]: 'danger'
  }
  return statusMap[status] || ''
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.mb-20px {
  margin-bottom: 20px;
}

.ml-10px {
  margin-left: 10px;
}

.mr-5px {
  margin-right: 5px;
}

.mb-5px {
  margin-bottom: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.app-id-text {
  font-family: 'Courier New', monospace;
  font-size: 14px;
}

.secret-container {
  display: flex;
  align-items: center;
}

.secret-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.secret-masked {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #909399;
}

.ip-list {
  line-height: 2;
}

.remark-content {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
  color: #606266;
}
</style>
